<template>
	<div class="import">
		<preview-images ref="previewImages" />
		<BaseForm ref="BaseFormRef" type="person" />
		<el-card class="box-card">
			<flexbox justify="space-between" slot="header">
				<span style="font-size: 16px; font-weight: bold">投保人</span>
				<el-switch v-model="isSelf" active-text="为自己投保"></el-switch>
			</flexbox>
			<el-form
				:model="holder"
				:rules="rules"
				label-width="80px"
				ref="holderForm"
			>
				<el-form-item label="投保人" prop="name" required>
					<el-input
						v-model="holder.name"
						size="mini"
						placeholder="请输入联系人"
						class="field"
					/>
				</el-form-item>
				<el-form-item label="证件类型" prop="idType" required>
					<el-select
						v-model="holder.idType"
						size="mini"
						filterable
						allow-create
						default-first-option
						class="field"
						placeholder="请选择证件类型"
					>
						<el-option
							v-for="idType in idTypeOptions"
							:key="idType.value"
							:value="idType.value"
							:label="idType.text"
						/>
					</el-select>
				</el-form-item>
				<el-form-item
					label="性别"
					prop="gender"
					v-if="holder.idType != 0"
					required
				>
					<el-select
						v-model="holder.gender"
						size="mini"
						filterable
						allow-create
						default-first-option
						class="field"
						placeholder="请选择性别"
					>
						<el-option
							v-for="gender in genderOptions"
							:key="gender.value"
							:value="gender.value"
							:label="gender.text"
						/>
					</el-select>
				</el-form-item>
				<el-form-item
					label="出生日期"
					prop="birth"
					v-if="holder.idType != 0"
					required
				>
					<el-date-picker
						v-model="holder.birth"
						size="mini"
						placeholder="请选择开始时间"
						type="date"
						value-format="yyyy-MM-dd"
						style="width: 100%"
					/>
				</el-form-item>

				<el-form-item label="证件号码" prop="idNum" required>
					<el-input
						v-model="holder.idNum"
						placeholder="请输入证件号码"
						size="mini"
						class="field"
					/>
				</el-form-item>

				<!-- <el-form-item label="手机号码" prop="phone" required>
					<el-input
						v-model="holder.phone"
						placeholder="请输入手机号码"
						size="mini"
						class="field"
					/>
				</el-form-item> -->
				<el-form-item label="常住地区" prop="city">
					<xh-address
						:value="holder.city"
						@value-change="({ value }) => (holder.city = value)"
					></xh-address>
				</el-form-item>
				<el-form-item label="详细地址" prop="detailAddress" required>
					<el-input
						v-model="holder.detailAddress"
						placeholder="请输入详细地址"
						size="mini"
						class="field"
					/>
				</el-form-item>

				<div style="grid-column: -1/1; text-align: center" v-if="isSelf">
					<el-button
						size="small"
						type="primary"
						@click="createOrder"
						:loading="submiting"
					>
						确认
					</el-button>
				</div>
			</el-form>
		</el-card>
		<el-card class="box-card" v-if="!isSelf">
			<div slot="header" class="clearfix">
				<span style="font-size: 16px; font-weight: bold"
					>被保人(家政服务人员)</span
				>
			</div>
			<el-form
				:model="relation"
				:rules="rules"
				label-width="80px"
				ref="relationForm"
			>
				<el-form-item
					label="服务人员姓名"
					prop="name"
					required
					label-width="106px"
				>
					<el-input
						v-model="relation.name"
						size="mini"
						placeholder="请输入联系人"
						class="field"
					/>
				</el-form-item>
				<el-form-item label="证件类型" prop="idType" required>
					<el-select
						v-model="relation.idType"
						size="mini"
						filterable
						allow-create
						default-first-option
						class="field"
						placeholder="请选择证件类型"
					>
						<el-option
							v-for="idType in idTypeOptions"
							:key="idType.value"
							:value="idType.value"
							:label="idType.text"
						/>
					</el-select>
				</el-form-item>
				<el-form-item
					label="性别"
					prop="gender"
					v-if="holder.idType != 0"
					required
				>
					<el-select
						v-model="relation.gender"
						size="mini"
						filterable
						allow-create
						default-first-option
						class="field"
						placeholder="请选择性别"
					>
						<el-option
							v-for="gender in genderOptions"
							:key="gender.value"
							:value="gender.value"
							:label="gender.text"
						/>
					</el-select>
				</el-form-item>
				<el-form-item
					label="出生日期"
					prop="birth"
					v-if="relation.idType != 0"
					required
				>
					<el-date-picker
						v-model="relation.birth"
						size="mini"
						placeholder="请选择出生日期"
						type="date"
						value-format="yyyy-MM-dd"
						style="width: 100%"
					/>
				</el-form-item>

				<el-form-item label="证件号码" prop="idNum" required>
					<el-input
						v-model="relation.idNum"
						placeholder="请输入证件号码"
						size="mini"
						class="field"
					/>
				</el-form-item>
				<div style="grid-column: -1/1; text-align: center">
					<el-button
						size="small"
						type="primary"
						@click="createOrder"
						:loading="submiting"
					>
						确认
					</el-button>
				</div>
			</el-form>
		</el-card>
		<el-dialog
			append-to-body
			width="250px"
			:close-on-click-modal="false"
			:visible.sync="showCodePopup"
			title="扫码支付"
		>
			<img
				:src="codeImageUrl"
				style="height: 160px; width: 160px; display: block; margin: 0 auto"
			/>
			<div class="text-center fs_small mt-2">使用微信扫描上方二维码</div>
			<div slot="footer" style="text-align: right">
				<el-button
					type="primary"
					size="mini"
					@click="payQuery"
					:loading="payQuerying"
					>我已支付</el-button
				>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import {
	productDetail,
	createBusiness,
	customerList,
	customerById,
	uploadFile,
	licenseOcr,
	sendSMSCode,
	saveInsure,
	saveBeibao,
	saveQixian,
	save,
	getBusinessById
} from '@/api'
import { mapGetters } from 'vuex'
import { createH5Order, goPay, payQuery } from '@/api/order'
import _ from 'lodash'
import * as REGEXP from '@/const/REGEXP'
import { queryCitys, queryAreaByCode } from '@/api/form'
import moment from 'moment'
import XhAddress from '@/components/createCom/XhAddress.vue'
var urlSearchParams = new URLSearchParams(location.search)
var UrlSearch = {}
for (let [key, value] of urlSearchParams.entries()) {
	UrlSearch[key] = value
}
const productId = 13253
import BaseForm from '../components/BaseForm.vue'
const baoform = {
	name: '', // 企业名称
	idNum: '', // 统一代码
	idType: 0,
	city: {},
	gender: '',
	birth: '',
	detailAddress: '', // 详细地址
	phone: '' // 手机号
}
export default {
	data() {
		var that = this

		const startTime = moment().add(1, 'days').format('yyyy-MM-DD')
		return {
			isSelf: true,
			holder: Object.assign({}, baoform),
			relation: Object.assign({}, baoform),

			rules: {
				name: [{ required: true, message: '请选择企业' }],
				idNum: [{ required: true, message: '请输入统一社会信用代码' }],
				detailAddress: [{ required: true, message: '请输入详细地址' }],
				// provinceCode: [{ required: true, message: '请选择省份' }],
				city: [{ required: true, message: '请选择地市' }],
				gender: [{ required: true, message: '请选择性别' }],
				birth: [{ required: true, message: '请选择出生日期' }],
				phone: [{ required: true, message: '请输入联系方式' }]
			},

			idTypeOptions: [
				{ text: '身份证', value: 0 },
				{ text: '护照', value: 2 },
				{ text: '外国人永久居留身份证', value: 11 },
				{ text: '武警身份证', value: 7 },
				{ text: '港澳通行证', value: 9 },
				{ text: '驾驶证', value: 14 },
				{ text: '港澳回乡证或台胞证', value: 8 },
				{ text: '临时身份证', value: 15 },
				{ text: '港澳台居民居住证', value: 10 }
			],
			genderOptions: [
				{ text: '男', value: 1 },
				{ text: '女', value: 2 }
			],
			// 支付选择

			showCodePopup: false,
			payQuerying: false,
			// 下单中
			submiting: false
		}
	},
	computed: {
		...mapGetters(['info']),

		endTime() {
			let startMoment = moment(this.startTime)
			if (this.period == '月') {
				startMoment = startMoment.add(1, 'months')
			} else if (this.period == '年') {
				startMoment = startMoment.add(1, 'years')
			}

			const endTime = startMoment.subtract(1, 'days').format('yyyy-MM-DD')
			console.log(endTime)
			return endTime
		}
	},
	async created() {
		productDetail(this.productId).then((res) => {
			this.productData = res.data

			// 开启录屏
			const channel = 'huanong'
			const oldChannel = localStorage.getItem('channel')

			if (oldChannel !== channel) {
				localStorage.setItem('channel', channel)
				Recorder.renew()
			}
			if (Recorder.status() !== 'living') {
				Recorder.start({
					channel: 'huanong',
					compress: true,
					testServer: 'https://service.aiins.cn/insurance/api/open/putJsonV2'
				})
			}
		})
	},
	mounted() {},
	watch: {
		info(val) {
			if (val.mobile) {
				this.createOrder()
			}
		}
	},
	methods: {
		async validate() {
			if (!this.info?.mobile) {
				this.$store.commit('SET_SHOW_LOGIN_TOAST', true)
				throw new Error('手机号未验证，展示验证弹窗')
			}
			await this.$refs.holderForm.validate()
			let holder = {
				...this.holder,
				province: this.holder.city.province,
				city: this.holder.city.city,
				district: this.holder.city.country
			}
			holder.phone = this.info.mobile
			let subject
			if (this.isSelf) {
				subject = holder
			} else {
				await this.$refs.relationForm.validate()
				subject = {
					...this.relation,
					province: this.relation.city.province,
					city: this.relation.city.city,
					district: this.relation.city.country
				}
			}

			let { startTime, endTime, activePlan } = this.$refs.BaseFormRef.getValue()

			return {
				order: {
					money: activePlan.premium,
					extendInfo: {},
					planId: activePlan.planId,
					startTime,
					endTime,
					holder,
					relations: [{ ...subject }],
					productId,
					// 地址栏参数
					...UrlSearch
				},
				// 家政人员是标的
				subjects: [{ ...subject }]
			}
		},
		// 填写完毕
		async createOrder() {
			if (this.submiting) {
				return
			}

			const submitData = await this.validate()

			this.submiting = true

			// 下单
			let { data: businessId, batchId } = await createH5Order(submitData)
			this.businessId = businessId
			try {
				await Recorder.submit({ businessId })
			} catch (e) {}

			// 去支付
			// 二维码地址
			goPay({ businessId, payType: 'pc' })
				.then(({ data: url }) => {
					this.codeImageUrl = url
					this.showCodePopup = true
				})
				.finally(() => {
					this.submiting = false
				})
		},
		// 查结果
		payQuery() {
			this.payQuerying = true
			const { businessId } = this
			payQuery({ businessId })
				.then(() => {
					this.$router.push({
						path: '/13253/success',
						query: { businessId }
					})
					Recorder.submit({
						businessId
					})
				})
				.catch((res) => {
					this.$confirm(res.msg, '温馨提示', {
						showCancelButton: false
					})
				})
				.finally(() => {
					this.payQuerying = false
				})
		}
	},
	components: { XhAddress, BaseForm }
}
</script>

<style lang="scss" scoped="scoped">
.box-card {
	margin-bottom: 20px;
}

.product-name {
	font-size: 20px;
	font-weight: 600;
	text-align: center;
	margin-block: 20px;
}

.import ::v-deep {
	.el-form {
		display: grid;
		gap: 15px;
		grid-template-columns: 1fr 1fr;
	}

	.el-form-item {
		margin-bottom: 0;
	}

	.el-table__header tr th {
		font-size: 13px;
		color: #333;
		background: #fbfcff;
	}

	._error_ {
		color: #f22 !important;
	}
}

.field {
	width: 100%;
}

.append-fix {
	position: absolute;
	right: 1em;
	top: 50%;
	transform: translateY(-50%);
	color: #999;
}

.hide-upload-button ::v-deep .el-upload--picture-card {
	display: none;
}
</style>
